package com.dunqi.gpm.cangxi.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.nanchen.compresshelper.CompressHelper;
import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.common.base.ComObserver;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.util.FormUtil;
import com.dunqi.gpm.cangxi.common.util.JsonUtils;
import com.dunqi.gpm.cangxi.common.util.RequestBodyUtil;
import com.dunqi.gpm.cangxi.common.util.TimeUtil;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;
import com.dunqi.gpm.cangxi.common.view.NoScrollGridView;
import com.dunqi.gpm.cangxi.home.adapter.PhotoAdapter;
import com.dunqi.gpm.cangxi.home.adapter.SpinnerAdapter;
import com.dunqi.gpm.cangxi.home.bean.Page;
import com.dunqi.gpm.cangxi.home.bean.YearPlan;
import com.dunqi.gpm.cangxi.home.constance.Constance;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

public class AddDayReportActivity extends BaseAct implements AdapterView.OnItemClickListener {

    private static final int REQUEST_CAMERA_CODE = 123;
    private static final int REQUEST_PREVIEW_CODE = 546;

    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.spinner)
    AppCompatSpinner spinner;
    @BindView(R.id.spinner2)
    AppCompatSpinner spinner2;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.remark_edit)
    EditText remarkEdit;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    private PhotoAdapter adapter;
    List<String> data = new ArrayList<>();
    private long projectId;
    ArrayList<YearPlan> yearPlans = new ArrayList<>();

    String[] progressTypes = {"进展类型", "未填写", "进展顺利", "基本正常", "进度滞后"};

    @Override
    protected void refreshData(Bundle savedInstanceState) {


        net();
    }

    private void net() {
        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在拉取数据");
        ApiFactory.getInstance()
                .queryProjectAnnualPlanList(projectId, null)
                .compose(RxSchedulers.<Page<YearPlan>>io_main())
                .subscribe(yearPlanPage -> {
                    dialog.dismiss();

                    ArrayList<YearPlan> list = yearPlanPage.getList();

                    yearPlans.clear();
                    yearPlans.addAll(list);

                    refreshUi();
                }, throwable -> {
                    dialog.dismiss();
                    t("获取失败");
                });

    }

    private void refreshUi() {
        String[] strings = new String[yearPlans.size()];


        int currentYear = TimeUtil.getCurrentYear();

        int index = 0;

        for (int i = 0; i < yearPlans.size(); i++) {
            int planYear = yearPlans.get(i).getPlanYear();
            strings[i] = planYear + "年年度计划";
            if (currentYear == planYear) {
                index = i;
            }
        }


        spinner.setAdapter(new SpinnerAdapter(this, strings));
        if (strings.length != 0) {
            spinner.setSelection(index);
        }
    }

    @Override
    protected void initUiAndListener() {

        projectId = getIntent().getLongExtra(Constance.PROJECTID, 0);

        data.add(null);
        adapter = new PhotoAdapter(getActivity(), data);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);


        spinner2.setAdapter(new SpinnerAdapter(this, progressTypes));
        spinner2.setVisibility(View.GONE);


        titleBar.setOnClickListenerOfRight(v -> commit());

    }

    private void commit() {
        HashMap<String, String> hashMap = new HashMap<>();

        String content = getContent();
        if (TextUtils.isEmpty(content)) {
            t("汇报内容不能为空");
            return;
        } else {
            hashMap.put("progressDesc", content);
        }

        hashMap.put("investedAmount", "0");
        hashMap.put("totalInvestmentAmount", "0");
        hashMap.put("currentPeriodInvested", "0");

        hashMap.put("applySettlement", "0");
        hashMap.put("projectId", String.valueOf(projectId));

//        investedAmount
//                totalInvestmentAmount
//        currentPeriodInvested


        String remark = getRemark();

        if (!TextUtils.isEmpty(remark)) {
            hashMap.put("remark", remark);
        }

        hashMap.put("reportType", "1");
        hashMap.put("progressType", "0");


        if (!yearPlans.isEmpty()) {
            int selectedItemPosition = spinner.getSelectedItemPosition();
            YearPlan yearPlan = yearPlans.get(selectedItemPosition);
            long proAnnualPlanId = yearPlan.getProAnnualPlanId();
            int planYear = yearPlan.getPlanYear();
            hashMap.put("proAnnualPlanId", "" + proAnnualPlanId);
            hashMap.put("planYear", "" + planYear);
        }

//        int selectedItemPosition1 = spinner2.getSelectedItemPosition();
//
//        if (selectedItemPosition1 == 0) {
//            t("请选择进展类型");
//            return;
//        } else {
//            hashMap.put("progressType", selectedItemPosition1 - 1 + "");
//        }

        hashMap.put("saveType", "submit");

        ArrayList<String> photos = getPhotos();

        String[] uploadFileRemark = new String[photos.size()];
        for (int i = 0; i < photos.size(); i++) {
            uploadFileRemark[i] = remark;
        }

        hashMap.put("uploadFileRemark", JsonUtils.toJson(uploadFileRemark));

        HashMap<String, RequestBody> requestBodyHashMap = FormUtil.AddHeader(hashMap);


        for (String photo : photos) {
            File file = CompressHelper.getDefault(this)
                    .compressToFile(new File(photo));
            requestBodyHashMap.put("uploadFile\"; filename=\"" + file.getName(), RequestBodyUtil.get(file));
        }

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在提交..");

        ApiFactory.getInstance()
                .createProgress(requestBodyHashMap)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new ComObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }

                    @Override
                    public void onSuccess(Object o) {
                        t("添加成功");
                        setResult(200);
                        finish();
                    }

                    @Override
                    public void onFinal() {
                        dialog.dismiss();
                    }
                });


    }

    public String getRemark() {
        return remarkEdit.getText().toString().trim();
    }

    public String getContent() {
        return contentEdit.getText().toString().trim();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = data.get(position);

        if (TextUtils.isEmpty(path)) {
            //
            PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照， 默认false
            intent.setMaxTotal(Constance.MAX_PIC); // 最多选择照片数量，默认为9
            ArrayList<String> paths = getPhotos();
            intent.setSelectedPaths(paths); // 已选中的照片地址， 用于回显选中状态
            // intent.setImageConfig(config);
            startActivityForResult(intent, REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
            intent.setCurrentItem(position - 1); // 当前选中照片的下标
            ArrayList<String> paths = getPhotos();
            intent.setPhotoPaths(paths); // 已选中的照片地址
            startActivityForResult(intent, REQUEST_PREVIEW_CODE);
        }
    }

    @NonNull
    private ArrayList<String> getPhotos() {
        ArrayList<String> paths = new ArrayList<>();
        paths.addAll(data);
        paths.remove(0);
        return paths;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
//            }
            }
        }
    }

    private void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        data.clear();
        data.add(null);
        data.addAll(paths);
        adapter.notifyDataSetChanged();
    }


    public static void start(Activity context, Long projectId) {
        Intent intent = new Intent(context, AddDayReportActivity.class);
        intent.putExtra(Constance.PROJECTID, projectId);
        context.startActivityForResult(intent, 111);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_day_report;
    }

}
